<!-- 图像数据 -->
<template>
	<view :class="['page', { iphoneX: isIphoneX }]">
		<template v-if="token && isLogin">
			<template v-if="type == 'data'">
				<view class="body">
					<view class="top">
						<navigator :url="'/package_common/search_tool/search_tool?dev_type=' + dev_type + '&typeid=' + select_dev.typeid" hover-class="none" class="top-banner">
							<view class="top-title">
								<view class="top-title-item1">{{ select_dev.name }}</view>
							</view>
							<view class="top-container">
								<view class="item top-containe-item1">
									<view class="f-wb f-s28">总数</view>
									<view class="val">
										<template v-if="countLoading.loading">
											<loading :loadingState="countLoading"></loading>
										</template>
										<template v-else>
											{{ pest_trend.tongji.zcount || '0' }}
										</template>
									</view>
								</view>
								<view class="item top-containe-item2">
									<view class="f-wb f-s28">今日新增</view>
									<view class="val">
										<template v-if="countLoading.loading">
											<loading :loadingState="countLoading"></loading>
										</template>
										<template v-else>
											{{ pest_trend.tongji.tcount || '0' }}
										</template>
									</view>
								</view>
								<view class="item top-containe-item3">
									<view class="f-wb f-s28">最近1周</view>
									<view class="val">
										<template v-if="countLoading.loading">
											<loading :loadingState="countLoading"></loading>
										</template>
										<template v-else>
											{{ pest_trend.tongji.wcount || '0' }}
										</template>
									</view>
								</view>
							</view>
						</navigator>
					</view>

					<view class="container">
						<view class="page__title">
							<view class="title">一周昆虫数量走势</view>
						</view>
						<view class="data-area">
							<template v-if="countLoading.loading">
								<view class="loading-box">
									<loading :loadingState="countLoading"></loading>
								</view>
							</template>
							<template v-else>
								<template v-if="pest_trend.ec_data.count">
									<uni-ec-canvas class="uni-ec-canvas" ref="canvas" canvas-id="lazy-load-chart" :ec="ec" :force-use-old-canvas="true"></uni-ec-canvas>
								</template>
								<template v-else>
									<view class="check-tips"><text>暂无统计数据</text></view>
								</template>
							</template>
						</view>
					</view>

					<view class="container">
						<view class="page__title">
							<view class="title">虫情识别情况</view>
							<navigator
								:url="'/package_pests/pest_data/pest_data?type=list&dev_name=' + select_dev.name + '&dev_id=' + select_dev.id + '&dev_type=' + dev_type"
								hover-class="none"
								class="btn">
								<view class="text">更多识别情况</view>
								<view class="icon">
									<image src="@/static/images/filter_icon.png" mode="widthFix"></image>
								</view>
							</navigator>
						</view>
						<view class="list-wrap">
							<template v-if="loadingState.default">
								<loading :loadingState="loadingState"></loading>
							</template>
							<template v-else>
								<template v-if="list.data.length > 0">
									<view class="item" v-for="(item, index) in list.data" :key="index">
										<view class="time">
											<view class="circel-icon"></view>
											<text>{{ item.addtime == null ? '--' : item.addtime }}</text>
										</view>
										<view class="content">
											<view class="text">
												<template v-if="item.pest_name">
													<text class="f-red">{{ item.pest_name + ' ' + item.num }}</text>
												</template>
												<template v-else>
													未发现昆虫
												</template>
											</view>
										</view>
									</view>
									<navigator
										:url="'/package_pests/pest_data/pest_data?type=list&dev_name=' + select_dev.name + '&dev_id=' + select_dev.id + '&dev_type=' + dev_type"
										hover-class="none"
										class="more-btn">
										更多识别情况
									</navigator>
								</template>
								<template v-else>
									<empty msg="暂无数据"></empty>
								</template>
							</template>
						</view>
					</view>
				</view>
			</template>

			<template v-if="type == 'list'">
				<view class="search-data">
					<view class="fix-wrap">
						<view class="change-btn">
							<view class="select-data">{{ select_dev.name }}</view>
							<view class="iconfont f-s24">&#xe623;</view>
						</view>
						<view class="date-bar">
							<view class="date start-date" @click="changeDate(1)">
								<input type="text" v-model="params.start_date" placeholder="选择开始时间" disabled="true" class="inp" />
							</view>
							<view class="date end-date" @click="changeDate(2)">
								<input type="text" v-model="params.end_date" placeholder="选择结束时间" disabled="true" class="inp" />
							</view>
							<view class="btn" @click="search">查询</view>
						</view>
					</view>
				</view>

				<view class="body">
					<view class="list-wrap">
						<template v-if="loadingState.default">
							<loading :loadingState="loadingState"></loading>
						</template>
						<template v-else>
							<template v-if="list.data.length > 0">
								<view class="item" v-for="(item, index) in list.data" :key="index">
									<view class="time">
										<view class="circel-icon"></view>
										<text>{{ item.addtime == null ? '--' : item.addtime }}</text>
									</view>
									<view class="content">
										<view class="text">
											<template v-if="item.pest_name">
												<text class="f-red">{{ item.pest_name + ' ' + item.num }}</text>
											</template>
											<template v-else>
												未发现昆虫
											</template>
										</view>
									</view>
								</view>
								<loading :loadingState="loadingState"></loading>
							</template>
							<template v-else>
								<empty msg="暂无数据"></empty>
							</template>
						</template>
					</view>
				</view>

				<!-- 弹窗 -->
				<view v-if="flag.isFullPage" class="full-fix-page a-fadein">
					<!-- 日期 -->
					<laydate v-if="flag.isSeleceDate" :type="params.date_type" @selectDate="selectDate" @closeDate="closeDate" @clearDate="clearDate"></laydate>
				</view>
			</template>
		</template>
	</view>
</template>

<script>
	import loading from '@/components/loading-more.vue';
	import laydate from '@/components/laydate.vue';
	import empty from '@/components/empty.vue';
	import uniEcCanvas from '@/components/uni-ec-canvas.vue';
	import * as echarts from '@/common/echart/echarts.js';
	let chart = null;
	export default {
		name: 'name',
		data() {
			return {
				type: '',
				token: uni.getStorageSync('token'),
				appid: getApp().globalData.appid,
				isIphoneX: getApp().globalData.isIphoneX,
				isLogin: false,
				userInfo: uni.getStorageSync('userInfo'),
				loginStateUpdate: false,
				loadingState: {
					default: true,
					loading: false,
					completed: false
				},
				countLoading: {
					loading: true
				},
				chartLoading: {
					loading: true
				},
				dev_type: '',
				detail: {},
				isShowSearch: false,
				params: {
					page: 1,
					limit: 20,
					order: 'desc',
					start_date: '',
					end_date: '',
					date_type: ''
				},
				flag: {
					// 弹窗相关
					isFullPage: false,
					isSeleceDate: false
				},
				list: {
					data: []
				},
				select_dev: {
					name: '',
					id: '',
					typeid: '',
					update: false
				},
				ec: {
					lazyLoad: true
				},
				pest_trend: {
					date: [],
					count: [],
					tongji: {}
				},
				week_data: {}
			};
		},
		async onLoad(params) {
			this.type = params.type;
			this.dev_type = params.dev_type;
			this.select_dev.id = params.dev_id;
			this.select_dev.name = params.dev_name;

			if (params.typeid) {
				this.select_dev.typeid = params.typeid;
			}

			if (this.token) {
				this.isLogin = await this.$loginState('check');
				if (this.isLogin) {
					if (this.type == 'data') {
						this.pest_trend = await this.getPestTongJi();
						console.log(this.pest_trend);
						this.getPestDataList();
						if (this.pest_trend.ec_data.count) {
							setTimeout(() => {
								this.$refs.canvas.init(this.initChart);
							}, 300);
						}
					} else if (this.type == 'list') {
						this.getPestDataList();
					}
				} else {
					this.isLogin = await this.$loginState('reset');
				}
			}
		},
		async onShow() {
			// 登录状态更新
			if (this.loginStateUpdate) {
				this.token = uni.getStorageSync('token');
				this.userInfo = uni.getStorageSync('userInfo');
				this.isLogin = true;
				if (this.type == 'data') {
					this.getPestDataList();
					this.pest_trend = await this.getPestTongJi();
					if (this.pest_trend.ec_data.count) {
						setTimeout(() => {
							this.$refs.canvas.init(this.initChart);
						}, 300);
					}
				} else if (this.type == 'list') {
					this.getPestDataList();
				}
				this.loginStateUpdate = false;
			}

			if (!this.token && !this.isLogin) {
				this.isLogin = await this.$loginState('reset');
			}

			// 设备切换
			if (this.select_dev.update) {
				this.dataInit();

				if (this.type == 'data') {
					this.getPestDataList();
					this.pest_trend = await this.getPestTongJi();
					if (this.pest_trend.ec_data.count) {
						setTimeout(() => {
							this.$refs.canvas.init(this.initChart);
						}, 300);
					}
				} else if (this.type == 'list') {
					this.getPestDataList();
				}
				this.select_dev.update = false;
			}
		},
		onReachBottom() {
			if (this.type == 'list') {
				if (this.loadingState.completed) {
					this.params.page = 0;
					return false;
				} else {
					this.params.page++;
					this.getPestDataList();
				}
			}
		},
		methods: {
			dataInit: function() {
				this.params.page = 1;
				this.list.data = [];
				this.loadingState.default = true;
				this.loadingState.loading = false;
				this.loadingState.completed = false;
				this.chartLoading.loading = true;
				this.countLoading.loading = true;
			},

			// 初始化echart图表
			initChart: function(canvas, width, height, canvasDpr) {
				chart = echarts.init(canvas, null, {
					width: width,
					height: height,
					devicePixelRatio: canvasDpr
				});
				canvas.setChart(chart);
				let { data, count } = this.pest_trend.ec_data;
				chart.setOption(this.setEchartOption(this.getCurrentWeek(), data, count));
				return chart;
			},

			// 设置echart配置
			setEchartOption: function() {
				let option = {
					grid: {
						x: 40,
						y: 20,
						x2: 20,
						y2: 40
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'line'
						}
					},
					xAxis: {
						type: 'category',
						data: this.pest_trend.date,
						axisLabel: {
							show: true,
							textStyle: {
								color: '#000'
							},
							interval: 0,
							rotate: 45 //倾斜度 -90 至 90 默认为0
						},
						axisLine: {
							lineStyle: {
								type: 'solid',
								color: '#000', //边线的颜色
								width: '1' //坐标线的宽度
							}
						}
					},
					yAxis: {
						type: 'value',
						minInterval: 1,
						axisLabel: {
							show: true,
							textStyle: {
								color: '#000'
							}
						},
						splitLine: {
							show: false
						},
						axisLine: {
							lineStyle: {
								type: 'solid',
								color: '#000', //边线的颜色
								width: '1' //坐标线的宽度
							}
						}
					},
					series: [{
						name: '',
						type: 'line',
						itemStyle: {
							normal: {
								lineStyle: {
									color: '#09f',
									width: 1
								}
							}
						},
						smooth: true,
						data: this.pest_trend.count
					}]
				};
				return option;
			},

			// echarts 配置多根线
			setEchartOption: function(xdata, ydata, num) {
				// let colorList = ['#09f', '#FE8C0E', '#2EC7C9', '#44B33E', '#B7F9DA', '#D71A4E', '#C7CCE9', '#D709E8', '#FFFF44'];
				// colorList.length = num;
				let series = [],
					legend_list = [],
					count = 0;
				for (let k in ydata) {
					series.push({
						name: k,
						type: 'line',
						itemStyle: {
							normal: {
								lineStyle: {
									// color: colorList[count],
									width: 1
								}
							}
						},
						smooth: true,
						data: ydata[k]
					});
					legend_list.push(k);
					count++;
				}

				let option = {
					// color: colorList,
					grid: {
						x: 40,
						y: 40,
						x2: 20,
						y2: 40
					},
					tooltip: {
						trigger: 'axis',
						axisPointer: {
							type: 'line'
						}
					},
					legend: {
						data: legend_list,
						type: 'scroll'
					},
					xAxis: {
						type: 'category',
						data: xdata,
						axisLabel: {
							show: true,
							textStyle: {
								color: '#000'
							},
							interval: 0,
							rotate: 45 //倾斜度 -90 至 90 默认为0
						},
						axisLine: {
							lineStyle: {
								type: 'solid',
								color: '#000', //边线的颜色
								width: '1' //坐标线的宽度
							}
						}
					},
					yAxis: {
						type: 'value',
						minInterval: 1,
						axisLabel: {
							show: true,
							textStyle: {
								color: '#000'
							}
						},
						splitLine: {
							show: false
						},
						axisLine: {
							lineStyle: {
								type: 'solid',
								color: '#000', //边线的颜色
								width: '1' //坐标线的宽度
							}
						}
					},
					series: series
				};
				return option;
			},

			//获取一周日期数组
			getCurrentWeek() {
				let date = new Date();
				var dateTime = date.getTime(); // 获取现在的时间
				var oneDayTime = 24 * 60 * 60 * 1000;
				var proWeekList = [];

				for (var i = 0; i < 7; i++) {
					var time = dateTime - (7 - i) * oneDayTime;
					proWeekList[i] = this.format(new Date(time)); //date格式转换为yyyy-mm-dd格式的字符串
				}
				return proWeekList;
			},

			format(time) {
				let date = new Date(time);
				let m = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth();
				let d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
				return `${m}-${d}`;
			},

			// 获取虫情 总数、周、日数量
			getPestTongJi: async function() {
				let res = await this.$api.tool_api.getPestTongJi({
					appid: this.appid,
					token: this.token,
					user_id: this.userInfo.uid,
					device_id: this.select_dev.id
				});

				if (res.data.ret == 1000) {
					console.log(res.data.data);
					this.countLoading.loading = false;

					let week = this.getCurrentWeek();
					console.log(week);
					let data = {},
						ec_data = {};
					if (res.data.data.weeklist.length > 0) {
						ec_data = res.data.data.weeklist.reduce((pre, cur) => {
							pre.data = pre.data || {};
							pre.count = pre.count || 0;

							if (pre.data[cur.pest_name]) {
								pre.data[cur.pest_name].push(cur);
							} else {
								pre.count++;
								pre.data[cur.pest_name] = [];
								pre.data[cur.pest_name].push(cur);
							}

							return pre;
						}, {});

						console.log("ec_data111", ec_data);

						let obj = {};
						for (let k in ec_data.data) {
							obj[k] = new Array(week.length).fill('0');
							for (let i = 0; i < ec_data.data[k].length; i++) {
								let index = week.indexOf(ec_data.data[k][i].addtime);
								if (index != -1) {
									obj[k][index] = ec_data.data[k][i].num;
								}
							}
						}
						console.log(obj);

						ec_data.data = obj;
						console.log('ec_data', ec_data);
					}

					data.tongji = res.data.data.tongji;
					data.ec_data = ec_data;
					return data;

					// this.pest_trend.tongji=res.data.data.tongji;
					// let date = [],
					// 	count = [],
					// 	data = {};
					// if(res.data.data.weeklist.length>0){
					// 	res.data.data.weeklist.forEach(item => {
					// 		date.push(item.addtime);
					// 		count.push(item.num)
					// 	})
					// 	data.date = date;
					// 	data.count = count;
					// }
					// data.tongji=res.data.data.tongji;
					// return data
				} else {
					this.countLoading.loading = false;
				}
			},

			// 获取虫情测报虫子列表
			getPestDataList: async function() {
				let res = await this.$api.tool_api.getPestDataList({
					appid: this.appid,
					token: this.token,
					user_id: this.userInfo.uid,
					page: this.params.page,
					limit: this.type == 'data' ? 10 : this.params.limit,
					device_id: this.select_dev.id,
					order: this.params.order,
					startDate: this.params.start_date,
					overDate: this.params.end_date
				});
				if (res.data.ret == 1000) {
					if (res.data.data) {
						this.list.data = this.list.data.concat(res.data.data);
						if (this.type == 'data') {
							this.loadingState.default = false;
							this.loadingState.loading = false;
							this.loadingState.completed = true;
						} else {
							if (res.data.data.length < this.params.limit) {
								this.loadingState.default = false;
								this.loadingState.loading = false;
								this.loadingState.completed = true;
							} else {
								this.loadingState.default = false;
								this.loadingState.loading = true;
							}
						}
					} else {
						this.loadingState.default = false;
					}
				} else if (res.data.ret == 1002) {
					this.loadingState.default = false;
					this.loadingState.loading = false;
					this.loadingState.completed = true;
				}
			},

			// 打开选择查询日期组件
			changeDate: function(type) {
				//type ==1 开始日期 2 终止日期
				this.params.date_type = type;
				this.showPopup('show', 'isSeleceDate');
			},

			showPopup: function(t, n) {
				if (t == 'show') {
					this.flag.isFullPage = true;
					this.flag[n] = true;
				} else if (t == 'hide') {
					for (let i in this.flag) {
						this.flag[i] = false;
					}
				}
			},

			// 选择日期
			selectDate: function(data) {
				this.showPopup('hide');
				if (data.type == 1) {
					if (Date.parse(this.end_date) < Date.parse(data.date)) {
						this.$showToast({
							title: '开始时间不能大于结束时间 ~'
						});
						this.params.start_date = '';
						return;
					} else {
						this.params.start_date = data.date;
					}
				} else {
					if (Date.parse(this.end_date) > Date.parse(data.date)) {
						this.$showToast({
							title: '结束时间不能小于开始时间 ~'
						});
						this.end_date = '';
						return;
					} else {
						this.params.end_date = data.date;
					}
				}
			},

			// 关闭日期控件
			closeDate: function() {
				this.showPopup('hide');
			},

			// 清空日期
			clearDate: function(data) {
				this.showPopup('hide');
				this.params.start_date = '';
				this.params.end_date = '';
			},

			search: function() {
				this.dataInit();
				this.getPestDataList();
			}
		},
		components: {
			loading,
			laydate,
			empty,
			uniEcCanvas
		},
		computed: {},
		watch: {}
	};
</script>

<style lang="less">
	page {
		background: #fff;
	}

	.search-date-area {
		.fix-wrap {
			height: 90rpx;
			background: #fff;
		}

		.date-bar {
			margin-top: 15rpx;
		}
	}

	.top {
		width: 100%;
		height: 350rpx;
		background-image: linear-gradient(to bottom, #1199fe, #fff);
		overflow: auto;
	}

	.top-banner {
		width: 92%;
		height: 240rpx;
		margin: 0 auto;
		margin-top: 60rpx;
		background-color: #fff;
		border-radius: 30rpx;
	}

	.top-title {
		width: 100%;
		height: 76rpx;
		border-bottom: 1rpx solid rgb(211, 211, 211);
		align-items: center;
	}

	.top-title-item1 {
		display: inline-block;
		font-weight: bold;
		width: 100%;
		height: 76rpx;
		line-height: 76rpx;
		text-align: center;
		font-size: 30rpx;
	}

	.top-container {
		width: 100%;
		height: 164rpx;
	}

	.top-container .item {
		float: left;
		width: 33.33%;
		height: 144rpx;
		padding-top: 20rpx;
		text-align: center;
	}

	.top-container .item .val {
		color: red;
		font-size: 36rpx;
		font-weight: bold;
		padding-top: 20rpx;
	}

	.top-containe-item1 {
		background-color: rgb(241, 247, 224);
		border-bottom-left-radius: 30rpx;
	}

	.top-containe-item2 {
		background-color: rgb(229, 248, 245);
	}

	.top-containe-item3 {
		background-color: rgb(231, 231, 231);
		border-bottom-right-radius: 30rpx;
	}

	.container {
		padding: 20rpx;
	}

	.page__title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		.title {
			font-size: 32rpx;
			font-weight: bold;
		}

		.btn {
			position: relative;
			display: flex;
			align-items: center;

			.text {
				margin-right: 8rpx;
				font-size: 28rpx;
				color: #999;
			}

			.icon {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 40rpx;
				height: 40rpx;

				image {
					width: 90%;
				}
			}
		}
	}

	.data-area {
		// height: 200px;
		height: 450rpx;

		.loading-box {
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	.list-wrap {
		padding: 20rpx;

		.item {
			margin-bottom: 40rpx;

			.time {
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;
				font-size: 30rpx;
				padding-left: 10rpx;

				.circel-icon {
					position: relative;
					left: -17rpx;
					width: 20rpx;
					height: 20rpx;
					border-radius: 50%;
					background-color: rgb(6, 172, 201);
				}
			}

			.content {
				padding: 0 0 0 30rpx;
				border-left: 2rpx dashed rgb(6, 172, 201);
			}

			.text {
				height: 70rpx;
				line-height: 70rpx;
				margin-bottom: 20rpx;
				padding: 0 20rpx;
				background: #eff6ff;
				color: #333;
				font-size: 30rpx;
			}
		}
	}

	.check-tips {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		font-size: 28rpx;
		color: #666;
	}

	.iphoneX {
		.more-btn {
			margin: 20rpx 0 50rpx;
		}
	}

	.more-btn {
		margin: 20rpx 0;
		text-align: center;
		font-size: 28rpx;
		color: #09f;
	}
</style>